Introduction to CSS

Comprehensive Explanation

CSS (Cascading Style Sheets) is a styling language used to describe the presentation of a document written in HTML or XML. It allows web developers to control the layout, colors, fonts, and other visual aspects of web pages, separate from the content structure defined by HTML.

Key points about CSS:

  • CSS stands for Cascading Style Sheets
  • It's used to style and layout web pages
  • CSS can control the layout of multiple web pages all at once
  • It's a cornerstone technology of the World Wide Web, alongside HTML and JavaScript

Line-by-Line Code Examples


/* This is a CSS comment */

body {
    font-family: Arial, sans-serif; /* Sets the font for the entire body */
    background-color: #f0f0f0; /* Sets a light gray background */
    margin: 0; /* Removes default margin */
    padding: 20px; /* Adds padding around the content */
}

h1 {
    color: #333; /* Dark gray color for headings */
    text-align: center; /* Centers the heading */
}

p {
    line-height: 1.6; /* Increases line spacing for readability */
    color: #666; /* Medium gray color for paragraph text */
}

.highlight {
    background-color: yellow; /* Adds a yellow background to elements with class "highlight" */
    font-weight: bold; /* Makes the text bold */
}
                

Line-by-Line Explanation

  1. body { ... }: Styles applied to the entire document body.
  2. font-family: Arial, sans-serif;: Sets the font to Arial, falling back to any sans-serif font if Arial isn't available.
  3. background-color: #f0f0f0;: Sets a light gray background color using a hexadecimal color code.
  4. margin: 0;: Removes the default margin around the body.
  5. padding: 20px;: Adds 20 pixels of padding inside the body.
  6. h1 { ... }: Styles applied to all <h1> elements.
  7. color: #333;: Sets the text color to a dark gray.
  8. text-align: center;: Centers the heading text.
  9. p { ... }: Styles applied to all <p> elements.
  10. line-height: 1.6;: Sets the line height to 1.6 times the font size for better readability.
  11. .highlight { ... }: Styles applied to elements with the class "highlight".
  12. background-color: yellow;: Sets a yellow background for highlighted elements.
  13. font-weight: bold;: Makes the text bold for highlighted elements.

Expected Outputs

When applied to an HTML document, this CSS will result in:

  • A light gray background for the entire page
  • All text in Arial font (or a sans-serif alternative)
  • Centered, dark gray headings
  • Paragraphs with increased line spacing and medium gray text
  • Any element with the class "highlight" will have a yellow background and bold text

Here's a visual representation:

Sample Heading

This is a sample paragraph demonstrating the CSS styles. Notice the increased line height and the gray color of the text.

Here's an example of a highlighted word using the .highlight class.